const utils = require('../libs/utils.js');
const BaseService = require('../libs/baseService.js');
const User = require('../models/user.js');
const CompanyUser = require('../models/company_user.js');
let service = new BaseService();

// 恢复某组织机构中的人员
service.addCompanyUser = async (ctx, next) => {
    try {
        const request = ctx.request.body;
        const user_id = request.user_id;
        const company_id = request.company_id;
        if (!user_id) {
            throw new Error('用户没有指定!');
        }

        let query = {company_id: company_id, user_id: user_id};
        // 先查询组织架构里面是否已经有该患者
        let has_exists = await CompanyUser.schema.findOne(query).exec();

        if (has_exists) {
            throw new Error('该用户已存在，不需要恢复!');
        }
        let insert_data = {
            "user_id": user_id,
            "company_id": company_id,
            "avatar": "/images/defaultHead.png",
        };
        
        let record = await User.schema.findById(user_id).exec();

        if (!record) {
            throw new Error("没有该用户在基础库!");
        } else {
            let employee_id = record.tuishiben_id;
            let real_employee_id = employee_id.split('_')[1];
            let phone_str = record.phones[0];
            insert_data.employee_id = real_employee_id;
            insert_data.nickname_en = record.nickname_en;
            insert_data.nickname = record.nickname;
            insert_data.created = utils.datetimeFormat();
            insert_data.modified = utils.datetimeFormat();
            insert_data.phoneno = phone_str;

            await CompanyUser.schema(insert_data).save();
            
            service.backSuccess(ctx, "修复缺失组织人员成功!");
            //throw new Error("已有该应用推送模板配置了！");
        }
    } catch(e) {
        console.error(e || e.message);
        service.backError(ctx, 500 , e.message);
    }

}

// 获取所有缺失组织机构人员
service.gitLostCompanyUsers = async (ctx, next) => {
    
}

// 通过company_id修复所有缺失组织机构人员
service.fixAllLostCompanyID = async (ctx, next) => {

}

